<?php

namespace app\service\queue;

use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

class AmqpSender
{
    public function publisher() {
        $queue = 'msgs';

        //$connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
        $connection = new AMQPStreamConnection(
            '120.25.227.106',
            5672,
            'guest',  //user
            'guest',  //password
            '/'  //vhost
        );
        $channel = $connection->channel();

        $channel->queue_declare($queue, false, true, false, false); //第3个参数设置为true，表示让消息队列持久化

        for ($i = 0; $i < 100; $i++) {
            $arr = [
                'id' => 'message_' . $i,
                'order_id' => str_replace('.', '' , microtime(true)) . mt_rand(10, 99) . $i,
                'content' => 'helloweba-' . time()
            ];
            $data = json_encode($arr);
            $msg = new AMQPMessage($data, ['delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT]); ////设置rabbitmq重启后也不会丢失队列，或者设置为'delivery_mode' => 2
            $channel->basic_publish($msg, '', $queue);

            echo 'Send message: ' . $data . PHP_EOL;
        }

        $channel->close();
        $connection->close();
    }
}